package com.example.mqmanager.controller;

import com.example.mqmanager.service.RedisManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/api/redis")
@CrossOrigin(origins = "*")
public class RedisManagerController {

    private static final Logger logger = LoggerFactory.getLogger(RedisManagerController.class);

    @Autowired
    private RedisManagerService redisManagerService;

    /**
     * 更新Redis配置
     */
    @PostMapping("/config")
    public ResponseEntity<String> updateRedisConfig(
            @RequestParam String host,
            @RequestParam int port,
            @RequestParam(required = false, defaultValue = "") String password,
            @RequestParam int database) {
        try {
            redisManagerService.updateRedisConfig(host, port, password, database);
            return ResponseEntity.ok("配置更新成功");
        } catch (Exception e) {
            logger.error("更新Redis配置时出错", e);
            return ResponseEntity.badRequest().body("配置更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有键
     */
    @GetMapping("/keys")
    public ResponseEntity<?> getKeys(
            @RequestParam(required = false, defaultValue = "*") String pattern,
            @RequestParam(required = false) String host,
            @RequestParam(required = false) Integer port,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) Integer database) {
        try {
            Set<String> keys;
            if (host != null && port != null && database != null) {
                keys = redisManagerService.getKeys(pattern, host, port, password != null ? password : "", database);
            } else {
                keys = redisManagerService.getKeys(pattern);
            }
            return ResponseEntity.ok(keys);
        } catch (Exception e) {
            logger.error("获取Redis键时出错", e);
            return ResponseEntity.badRequest().body("获取Redis键时出错: " + e.getMessage());
        }
    }

    /**
     * 获取键的值
     */
    @GetMapping("/keys/{key}")
    public ResponseEntity<?> getValue(
            @PathVariable String key,
            @RequestParam(required = false) String host,
            @RequestParam(required = false) Integer port,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) Integer database) {
        try {
            // ttl: 过期时间(秒)，-1表示永不过期，-2表示键不存在
            // type: 数据类型(string/hash/list/set/zset)
            // value: 实际存储的值，根据数据类型返回相应格式
            Object value;
            Long ttl = null;
            String type = null;
            if (host != null && port != null && database != null) {
                value = redisManagerService.getValue(key, host, port, password != null ? password : "", database);
            } else {
                Map<String, Object> result = redisManagerService.getValueAndTTL(key);
                ttl = (Long) result.get("ttl");
                value = result.get("value");
                type = (String) result.get("type");
            }
            Map<String, Object> result = new HashMap<>();
            result.put("key", key);
            result.put("value", value);
            result.put("ttl", ttl);
            result.put("type", type);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取Redis键值时出错: " + key, e);
            Map<String, Object> result = new HashMap<>();
            result.put("key", key);
            result.put("error", "获取Redis键值时出错: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 删除键
     */
    @DeleteMapping("/keys/{key}")
    public ResponseEntity<?> deleteKey(
            @PathVariable String key,
            @RequestParam(required = false) String host,
            @RequestParam(required = false) Integer port,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) Integer database) {
        try {
            boolean deleted;
            if (host != null && port != null && database != null) {
                deleted = redisManagerService.deleteKey(key, host, port, password != null ? password : "", database);
            } else {
                deleted = redisManagerService.deleteKey(key);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", deleted);
            if (deleted) {
                result.put("message", "键删除成功");
            } else {
                result.put("message", "键删除失败");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("删除Redis键时出错: " + key, e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", "删除Redis键时出错: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 批量删除键
     */
    @DeleteMapping("/keys")
    public ResponseEntity<?> deleteKeys(
            @RequestBody(required = false) Set<String> keys,
            @RequestParam(required = false) String host,
            @RequestParam(required = false) Integer port,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) Integer database) {
        try {
            if (keys == null || keys.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("error", "键列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            long deletedCount;
            if (host != null && port != null && database != null) {
                deletedCount = redisManagerService.deleteKeys(keys, host, port, password != null ? password : "", database);
            } else {
                deletedCount = redisManagerService.deleteKeys(keys);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("deletedCount", deletedCount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("批量删除Redis键时出错", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", "批量删除Redis键时出错: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 设置键值对
     */
    @PostMapping("/keys")
    public ResponseEntity<?> setValue(
            @RequestParam String key,
            @RequestParam String value,
            @RequestParam(required = false) String host,
            @RequestParam(required = false) Integer port,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) Integer database) {
        try {
            boolean success;
            if (host != null && port != null && database != null) {
                success = redisManagerService.setValue(key, value, host, port, password != null ? password : "", database);
            } else {
                success = redisManagerService.setValue(key, value);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            if (success) {
                result.put("message", "键值对设置成功");
            } else {
                result.put("message", "键值对设置失败");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("设置Redis键值时出错: " + key, e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", "设置Redis键值时出错: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
}